<?php

namespace app\xcxapi\service;

use app\common\service\BaseService;
use app\lib\exception\BaseException;
use app\models\AllocationCampusModel;
use app\models\AllocationOnlyModel;
use app\models\CampusModel;
use app\models\ContractModel;
use app\models\CourseContractModel;
use app\models\CourseModel;
use app\models\DictionaryModel;
use app\models\GoodsContractModel;
use app\models\GoodsModel;
use app\models\GradesContractModel;
use app\models\GradesDetailsModel;
use app\models\CapitalRecordListModel;
use app\models\ReceivablesModel;
use app\models\RefundAmountModel;
use app\models\StudentModel;
use app\models\UserModel;
use think\Db;

class FinanceService extends BaseService
{
    /**
     * 财务汇总
     * User: wufeng
     * Date: 2020/02/21.
     *
     * @param $params
     *
     * @return array
     */
    public function financeSummary($params)
    {
        try {
            $where = $where_ = [];
            if (5 === (int) xcxapi_get_current_wtype()) {
                $where['contractor'] = xcxapi_get_current_user_id();
                $where_['payee'] = xcxapi_get_current_user_id();
            } else {
                $where['campus_id'] = ['in', xcxapi_get_current_campus_id()];
                $where_['campus_id'] = ['in', xcxapi_get_current_campus_id()];
            }
            //应收总金额
            $this->data['receivable'] = ((new ContractModel())->where($where)->sum('total_amount')) / 100;
            //实收总金额
            $this->data['net_receipts'] = ((new ReceivablesModel())->where($where_)->sum('amount')) / 100;

            $dictionary = (new DictionaryModel())->where(['type' => 20])->select()->toArray();

            $amount = 0;
            foreach ($dictionary as &$item) {
                $item['pay_type'] = $item['name'];
                $where_['payment_method'] = $item['id'];
                $money = ((new ReceivablesModel())->where($where_)->sum('amount') / 100);
                $amount = $amount + $money;
                $item['amount_money'] = $money;
            }

            $item_end = [];
            $item_end['pay_type'] = '合计';
            $item_end['amount_money'] = $amount;
            $dictionary[\count($dictionary)] = $item_end;
            $this->data['payment_method'] = $dictionary;
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 校区收款汇总
     * User: wufeng
     * Date: 2020/02/21.
     *
     * @param $params
     *
     * @return array
     */
    public function campusReceivablesSummary($params)
    {
        try {
            $where = [];
            $where_allocation = [];
            if (5 === (int) xcxapi_get_current_wtype()) {
                $where['id'] = xcxapi_get_current_campus_id();
                $where_allocation['campus_id_all'] = xcxapi_get_current_campus_id();
            } else {
                $where['id'] = ['in', xcxapi_get_current_campus_id()];
                $where_allocation['campus_id_all'] = ['in', xcxapi_get_current_campus_id()];
            }
            $where['status'] = 1;
            $campus_amount_all = (new AllocationCampusModel())->where($where_allocation)->sum('rate_all_money'); //业绩总额
            $allocationCampus = (new CampusModel())
				->where($where)
				->order('id desc')
				->select()
				->toArray();
            foreach ($allocationCampus as &$item) {
                $rate_all_money = (new AllocationCampusModel())->where(['campus_id_all' => $item['id']])->sum('rate_all_money'); //校区业绩
                $amount_already_all = (new AllocationCampusModel())->where(['campus_id_all' => $item['id']])->sum('amount_already_all'); //校区实收金额
                if ($campus_amount_all <= 0) {
                    $item['rate_all'] = '0.00%';
                } else {
                    $campus_rate = ($rate_all_money / $campus_amount_all);
                    $item['rate_all'] = (round($campus_rate, 2) * 100).'%';
                }
                $item['amount_already_all'] = $amount_already_all / 100;
                $item['rate_all_money'] = $rate_all_money / 100;
            }

            $this->data['allocationCampus'] = $allocationCampus;
            $this->data['total_amount'] = $campus_amount_all / 100;
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 个人收款汇总
     * User: wufeng
     * Date: 2020/02/21.
     *
     * @param $params
     *
     * @return array
     */
    public function personalReceivablesSummary($params)
    {
        try {
            $where = [];
            if (5 === (int) xcxapi_get_current_wtype()) {
                $where['campus_id'] = xcxapi_get_current_campus_id();
                $where['payee_only'] = xcxapi_get_current_user_id();
            } else {
                $where['campus_id'] = ['in', xcxapi_get_current_campus_id()];
            }
            $only_amount_all = (new AllocationOnlyModel())->where($where)->sum('rate_only_money'); //业绩总额
            $user_array = (new AllocationOnlyModel())->where($where)->column('payee_only');
            $user_array = array_values(array_unique($user_array)); //学员去重
            $allocationOnly = [];
            for ($i = 0; $i < \count($user_array); ++$i) {
                $item = [];
                $rate_only_money = (new AllocationOnlyModel())->where(['payee_only' => $user_array[$i]])->sum('rate_only_money'); //个人业绩
                    $amount_already_only = (new AllocationOnlyModel())->where(['payee_only' => $user_array[$i]])->sum('amount_already_only'); //个人实收金额
                    if ($only_amount_all <= 0) {
                        $item['rate_only'] = '0.00%';
                    } else {
                        $only_rate = ($rate_only_money / $only_amount_all);
                        $item['rate_only'] = (round($only_rate, 2) * 100).'%';
                    }
                $item['amount_already_only'] = $amount_already_only / 100;
                $item['rate_only_money'] = $rate_only_money / 100;
                $item['payee_only_text'] = (new UserModel())->get(['id' => $user_array[$i]])['name'];
                $allocationOnly[] = $item;
            }

            $this->data['allocationOnly'] = $allocationOnly;
            $this->data['total_amount'] = $only_amount_all / 100;
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }
	
	
	 /**
     * 资金分配记录
     * User: chenben
     * Date: 2020/04/25.
     *
     * @param $params
     *
     * @return array
     */
    public function getContractinfo($params)
    {
        try {
			
			$where = [];
			$where['contract_number'] = $params['contract_number'];
            $listData  = (new ContractModel())
                ->where($where)
				->order('id desc')
                ->select()
                ->toArray();
			
			$course_arr = '';
			$grades_course = '';
			$course_paid_nums = '';
			$grades_course_paid_nums = '';
			$course_elimination_nums = '';
			$grades_course_elimination_nums = '';

			$contract_id = '';
			$stay_distributed = 0;
			$CourseContractModel = new CourseContractModel();
			$GradesContractModel = new GradesContractModel();
			if (!empty($listData)) {
				foreach ($listData as &$item) {
					$contract_id = $item['id'];  //合同ID
					$course_arr = explode(',',$item['course']);
					$course_paid_nums = explode(',',$item['course_paid_nums']);;  //到款数量
					$grades_course = explode(',',$item['grades_course']);
					$grades_course_paid_nums =  explode(',',$item['grades_course_paid_nums']);;  //到款数量
					$course_elimination_nums = explode(',',$item['course_elimination']); //剩余课消
					$grades_course_elimination_nums = explode(',',$item['grades_course_elimination']); //剩余课消
					$stay_distributed = $item['stay_distributed'];
				}
			}

			$res_course = $CourseContractModel->where(['contract_id' => $contract_id])->select();
			$res_grades = $GradesContractModel->where(['contract_id' => $contract_id])->select();

			$listData_ = [];
			//课程
			foreach ($res_course as $value){
				$item_course = [];
				$item_course['project_id'] = $value['id'];
				$item_course['project_name'] = CourseModel::get(['id' => $value['course_id']])['course_name'];
				$item_course['project_nums']  = $value['class_num'];  //签约数量
				$item_course['project_type']  = 1;  //类型1：课程
				//算单价
				$item_course['project_price'] = round(((($value['net_receipts'] - $value['assessed_amount'])/($value['class_num']))/100),2); //(折后应收 - 分摊金额)/nums
				$item_course['project_total_amount'] = ($value['net_receipts'] - $value['assessed_amount']) / 100; //应收金额

				$key = array_search($value['course_id'], $course_arr);
				$item_course['project_paid_nums'] = $course_paid_nums[$key];  //到款数量
				$item_course['project_paid_amount'] = $value['payment'] / 100; //到款金额

				$item_course['project_surplus_nums'] = $course_elimination_nums[$key];  //剩余数量
				$item_course['project_surplus_amount'] = $value['payment_balance'] / 100; //剩余金额

				$item_course['project_stay_distributed'] = $stay_distributed;

				$listData_[] = $item_course;
			}

			//班级
			foreach ($res_grades as $value){
				$item_grades = [];
				$item_grades['project_id'] = $value['id'];
				$item_grades['project_name'] = GradesDetailsModel::get(['id' => $value['grades_id']])['grades_name'];
				$item_grades['project_nums']  = $value['class_num'];  //签约数量
				$item_grades['project_type']  = 2;  //类型1：班级
				//算单价
				$item_grades['project_price'] = round(((($value['net_receipts'] - $value['assessed_amount'])/($value['class_num']))/100),2); //(折后应收 - 分摊金额)/nums
				$item_grades['project_total_amount'] = ($value['net_receipts'] - $value['assessed_amount']) / 100; //应收金额

				$key = array_search($value['course_id'], $grades_course);
				$item_grades['project_paid_nums'] = $grades_course_paid_nums[$key];  //到款数量
				$item_grades['project_paid_amount'] = $value['payment'] / 100; //到款金额

				$item_grades['project_surplus_nums'] = $grades_course_elimination_nums[$key];  //剩余数量
				$item_grades['project_surplus_amount'] = $value['payment_balance'] / 100; //剩余金额

				$item_course['project_stay_distributed'] = $stay_distributed;

				$listData_[] = $item_grades;
			}
			$this->data['info'] = $listData_;
			$this->data['contract_info'] = $listData;
          
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }
	
	
	/**
     * 提交资金分配记录
     * User: chenben
     * Date: 2020/04/25.
     *
     * @param $params
     *
     * @return array
     */
    public function referAllocation($params)
    {
        try {
			if($params['api_type'] == 1){  //资金回抽
				$money_ = $params['money_'] * 100;  //回抽资金
				$num_ = $params['num_'];  //回抽数量
				$project_id = $params['project_id'];  //项目id
				$project_type = $params['project_type'];  //项目类型
				$contract_number = $params['contract_number'];  //订单编号
				$campus_id = $params['campus_id'];  //分配校区

				$nums = 0;
				$course_id_ = 0;
				if($project_type == 1){  //课程
					$res_course = (new CourseContractModel())->get(['id' => $project_id]);
					$res_course['payment'] = $res_course['payment'] - $money_;  //到款金额
					$payment_amount = $res_course['payment'];
					//更新合同应收分配课时
					$price_ = round(((($res_course['net_receipts'] - $res_course['assessed_amount']))/($res_course['class_num'])),2); //折后应收 - 分摊金额
					$nums = round(($payment_amount / $price_),2);
					$course_id_ = $res_course['course_id'];
					$res_course['payment_balance'] = $res_course['payment_balance'] - $money_;  //余额
					if(!(new CourseContractModel())->where(['id' => $project_id])->update(['payment' => $res_course['payment'], 'payment_balance' => $res_course['payment_balance']])){
						throw new BaseException('UPDATE_COURSE_PROJECT_FAILED');
					}
				}else if($project_type == 2){  //班级
					$res_grades = (new GradesContractModel())->get(['id' => $project_id]);
					$res_grades['payment'] = $res_grades['payment'] - $money_;  //到款金额
					$payment_amount = $res_grades['payment'];
					$price_ = round(((($res_grades['net_receipts'] - $res_grades['assessed_amount']))/($res_grades['class_num'])),2); //折后应收 - 分摊金额
					$nums = round(($payment_amount / $price_),2);
					$course_id_ = $res_grades['course_id'];
					$res_grades['payment_balance'] = $res_grades['payment_balance'] - $money_;  //余额
					if(!(new GradesContractModel())->where(['id' => $project_id])->update(['payment' => $res_grades['payment'], 'payment_balance' => $res_grades['payment_balance']])){
						throw new BaseException('UPDATE_GRADES_PROJECT_FAILED');
					}
				}

				$result = (new ContractModel())->get(['contract_number' => $contract_number]);
				$stay_distributed = $result['stay_distributed'] + $money_; //待分配金额
				$course_arr = explode(',',$result['course']);  //课程
				$course_paid_nums_arr = explode(',',$result['course_paid_nums']);  //到款数量
				$grades_course_arr = explode(',',$result['grades_course']); //班级
				$grades_course_paid_nums_arr = explode(',',$result['grades_course_paid_nums']);  //到款数量


				//学费余额
				$payment_grades_balance = (new GradesContractModel())->where(['contract_id' => $result['id']])->sum('payment_balance');
				$payment_course_balance = (new CourseContractModel())->where(['contract_id' => $result['id']])->sum('payment_balance');
				$payment_money_balance = ($payment_course_balance + $payment_grades_balance); //班级与课程余额之和


				if($project_type == 1){ //课程
					$key = array_search($course_id_, $course_arr);
					$course_paid_nums_arr[$key] = $nums;
					$course_paid_str = implode(',',$course_paid_nums_arr);
					$result['amount'] = $result['amount']  - $money_;  //项目总收费
					$result['net_receipts'] = $result['amount'];  //实际收费
					$result['balance'] = $payment_money_balance;  //学费余额
					if(!(new ContractModel())->where(['id' => $result['id']])->update(['course_paid_nums' => $course_paid_str, 'stay_distributed' => $stay_distributed, 'amount' => $result['amount'], 'net_receipts' => $result['net_receipts'], 'balance' => $result['balance']])){
						throw new BaseException('UPDATE_CONTRACT_PAY_COURSE_PROJECT_FAILED');
					}
				}else if($project_type == 2){  //班级
					$key = array_search($course_id_, $grades_course_arr);
					$grades_course_paid_nums_arr[$key] = $nums;
					$grades_course_paid_str = implode(',',$grades_course_paid_nums_arr);
					$result['amount'] = $result['amount']  - $money_;  //项目总收费
					$result['net_receipts'] = $result['amount'];  //实际收费
					$result['balance'] = $payment_money_balance;  //学费余额
					if(!(new ContractModel())->where(['id' => $result['id']])->update(['grades_course_paid_nums' => $grades_course_paid_str, 'stay_distributed' => $stay_distributed, 'amount' => $result['amount'], 'net_receipts' => $result['net_receipts'], 'balance' => $result['balance']])){
						throw new BaseException('UPDATE_CONTRACT_PAY_GRADES_PROJECT_FAILED');
					}
				}
				$capital_allocation_id = time();
				//插入资金分配记录
				$data = [
					'campus_id' => $campus_id,  //签约校区
					'contractor' => $result['contractor'],  //签约人
					'student_name' => $result['student_name'],  //学员姓名
					'contract_number' => $contract_number,
					'capital_allocation_id' => $capital_allocation_id,
					'distributive_person' => xcxapi_get_current_user_id(),  //获取当前登录用户ID
					'project_id' => $project_id,  //项目ID
					'project_type' => $project_type,  //项目类型
					'allocation_fund' => -$money_,
					'allotted_quantity' => $num_,
				];
				(new CapitalRecordListModel())->create($data);  //插入记录
				
			}else if($params['api_type'] == 2){  //资金分配
				$money_ = $params['money_'] * 100;  //分配资金
				$num_ = $params['num_'];  //分配数量
				$project_id = $params['project_id'];  //项目id
				$project_type = $params['project_type'];  //项目类型
				$contract_number = $params['contract_number'];  //订单编号
				$campus_id = $params['campus_id'];  //分配校区

				$nums = 0;
				$course_id_ = 0;
				if($project_type == 1){  //课程
					$res_course = (new CourseContractModel())->get(['id' => $project_id]);
					$res_course['payment'] = $res_course['payment'] + $money_;  //到款金额
					$payment_amount = $res_course['payment'];
					//更新合同应收分配课时
					$price_ = round(((($res_course['net_receipts'] - $res_course['assessed_amount']))/($res_course['class_num'])),2); //折后应收 - 分摊金额
					$nums = round(($payment_amount / $price_),2);
					$course_id_ = $res_course['course_id'];
					$res_course['payment_balance'] = $res_course['payment_balance'] + $money_;  //余额
					if(!(new CourseContractModel())->where(['id' => $project_id])->update(['payment' => $res_course['payment'], 'payment_balance' => $res_course['payment_balance']])){
						throw new BaseException('UPDATE_COURSE_PROJECT_FAILED');
					}
				}else if($project_type == 2){  //班级
					$res_grades = (new GradesContractModel())->get(['id' => $project_id]);
					$res_grades['payment'] = $res_grades['payment'] + $money_;  //到款金额
					$payment_amount = $res_grades['payment'];
					$price_ = round(((($res_grades['net_receipts'] - $res_grades['assessed_amount']))/($res_grades['class_num'])),2); //折后应收 - 分摊金额
					$nums = round(($payment_amount / $price_),2);
					$course_id_ = $res_grades['course_id'];
					$res_grades['payment_balance'] = $res_grades['payment_balance'] + $money_;  //余额
					if(!(new GradesContractModel())->where(['id' => $project_id])->update(['payment' => $res_grades['payment'], 'payment_balance' => $res_grades['payment_balance']])){
						throw new BaseException('UPDATE_GRADES_PROJECT_FAILED');
					}
				}

				$result = (new ContractModel())->get(['contract_number' => $contract_number]);
				$stay_distributed = $result['stay_distributed'] - $money_; //待分配金额
				$course_arr = explode(',',$result['course']);  //课程
				$course_paid_nums_arr = explode(',',$result['course_paid_nums']);  //到款数量
				$grades_course_arr = explode(',',$result['grades_course']); //班级
				$grades_course_paid_nums_arr = explode(',',$result['grades_course_paid_nums']);  //到款数量


				//学费余额
				$payment_grades_balance = (new GradesContractModel())->where(['contract_id' => $result['id']])->sum('payment_balance');
				$payment_course_balance = (new CourseContractModel())->where(['contract_id' => $result['id']])->sum('payment_balance');
				$payment_money_balance = ($payment_course_balance + $payment_grades_balance); //班级与课程余额之和


				if($project_type == 1){ //课程
					$key = array_search($course_id_, $course_arr);
					$course_paid_nums_arr[$key] = $nums;
					$course_paid_str = implode(',',$course_paid_nums_arr);
					$result['amount'] = $result['amount']  + $money_;  //项目总收费
					$result['net_receipts'] = $result['amount'];  //实际收费
					$result['balance'] = $payment_money_balance;  //学费余额
					if(!(new ContractModel())->where(['id' => $result['id']])->update(['course_paid_nums' => $course_paid_str, 'stay_distributed' => $stay_distributed, 'amount' => $result['amount'], 'net_receipts' => $result['net_receipts'], 'balance' => $result['balance']])){
						throw new BaseException('UPDATE_CONTRACT_PAY_COURSE_PROJECT_FAILED');
					}
				}else if($project_type == 2){  //班级
					$key = array_search($course_id_, $grades_course_arr);
					$grades_course_paid_nums_arr[$key] = $nums;
					$grades_course_paid_str = implode(',',$grades_course_paid_nums_arr);
					$result['amount'] = $result['amount']  + $money_;  //项目总收费
					$result['net_receipts'] = $result['amount'];  //实际收费
					$result['balance'] = $payment_money_balance;  //学费余额
					if(!(new ContractModel())->where(['id' => $result['id']])->update(['grades_course_paid_nums' => $grades_course_paid_str, 'stay_distributed' => $stay_distributed, 'amount' => $result['amount'], 'net_receipts' => $result['net_receipts'], 'balance' => $result['balance']])){
						throw new BaseException('UPDATE_CONTRACT_PAY_GRADES_PROJECT_FAILED');
					}
				}
				$capital_allocation_id = time();
				//插入资金分配记录
				$data = [
					'campus_id' => $campus_id,  //签约校区
					'contractor' => $result['contractor'],  //签约人
					'student_name' => $result['student_name'],  //学员姓名
					'contract_number' => $contract_number,
					'capital_allocation_id' => $capital_allocation_id,
					'distributive_person' => xcxapi_get_current_user_id(),  //获取当前登录用户ID
					'project_id' => $project_id,  //项目ID
					'project_type' => $project_type,  //项目类型
					'allocation_fund' => $money_,
					'allotted_quantity' => $num_,
				];
				(new CapitalRecordListModel())->create($data);  //插入记录
				
			}
				
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }



    /**
     * 退款汇总
     * User: wufeng
     * Date: 2020/02/21.
     *
     * @param $params
     *
     * @return array
     */
    public function refundSummary($params)
    {
        try {
            $where = [];
            if (5 === (int) xcxapi_get_current_wtype()) {
                $where['experienced_person'] = xcxapi_get_current_user_id();
            } else {
                $where['campus_id'] = ['in', xcxapi_get_current_campus_id()];
            }
            $refund_amount_all = ((new RefundAmountModel())->where($where)->sum('refund_amount')) / 100;
            $allocationOnly = (new RefundAmountModel())
                ->where($where)
				->order('id desc')
                ->select()
                ->toArray();

            foreach ($allocationOnly as &$item) {
                $refund_amount = ((new RefundAmountModel())->get($item['id'])['refund_amount']) / 100;
                if ($refund_amount_all <= 0) {
                    $item['rate_refund'] = '0.00%';
                } else {
                    $rate_refund = ($refund_amount / $refund_amount_all);
                    $item['rate_refund'] = (round($rate_refund, 2) * 100).'%';
                }
                $item['refund_amount'] = $item['refund_amount'] / 100;
            }
            $this->data['allocationOnly'] = $allocationOnly;
            $this->data['total_amount'] = $refund_amount_all;
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 缴款确认
     * User: wufeng
     * Date: 2020/02/21.
     *
     * @param $params
     *
     * @return array
     */
    public function paymentConfirmation($params)
    {
        try {
            if (5 === (int) xcxapi_get_current_wtype()) {
                $where['payee'] = xcxapi_get_current_user_id();
            } else {
                $where['campus_id'] = ['in', xcxapi_get_current_campus_id()];
            }
            $this->data = (new ReceivablesModel())
                ->where($where)
				->order('id desc')
                ->select()
                ->toArray();
            foreach ($this->data as &$datum) {
                $datum['student_name'] = (new ContractModel())->get(['contract_number' => $datum['contract_number']])['student_name'];
                $datum['campus_name'] = (new CampusModel())->get(['id' => $datum['campus_id']])['campus_name'];
                $datum['user_name'] = (new UserModel())->get(['id' => $datum['payee']])['name'];
                $datum['payment_method'] = (new DictionaryModel())->get(['id' => $datum['payment_method']])['name'];
                $datum['amount'] = $datum['amount'] / 100;
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 审核
     * User: wufeng
     * Date: 2020/03/20.
     *
     * @param $params
     *
     * @return array
     */
    public function examine($params)
    {
        try {
            (new ReceivablesModel())->save(['status' => 2], ['id' => $params['id']]);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 订单记录
     * User: wufeng
     * Date: 2020/02/21.
     *
     * @param $params
     *
     * @return array
     */
    public function orderLists($params)
    {
        try {
            //订单状态
			$where = [];
            if (isset($params['api_type']) && '' !== $params['api_type']) {
                if (1 == $params['api_type']) {
                    //全部
                    $where['status'] = ['in', '1,2,3'];
                } elseif (2 == $params['api_type']) {
                    //未收款
                    $where['status'] = 2;
                } elseif (3 == $params['api_type']) {
                    //部分收款
                    $where['status'] = 3;
                }
            }
            if (5 == (int) xcxapi_get_current_wtype()) {
                $where['contractor'] = xcxapi_get_current_user_id();
            } else if(1 != (int) xcxapi_get_current_wtype() && 5 != (int) xcxapi_get_current_wtype()){
				$where['campus_id'] = ['in', xcxapi_get_current_campus_id()];
            }
		
            $this->data = (new ContractModel())
                ->where($where)
				->order('id desc')
                ->select()
                ->toArray();
            foreach ($this->data as &$datum) {
                if (false !== strpos($datum['contract_number'], 'CZ')) {
                    $datum['order_status'] = 2;
                } else {
                    $datum['order_status'] = 1;
                }
				$datum['contractor'] = (new UserModel())->get($datum['contractor'])['name'];
				$datum['student_phone'] = (new StudentModel())->get($datum['student_id'])['phone'];
				$datum['campus_name'] = (new CampusModel())->get($datum['campus_id'])['campus_name'];
				if($datum['input_type'] == 0){
					$datum['input_type_text'] = '新生';
				}else if($datum['input_type'] == 1){
					$datum['input_type_text'] = '老生';
				}
                $datum['course_contract_sign_up'] = (new CourseContractModel())
                    ->where(['contract_id' => $datum['id']])
                    ->select()
                    ->toArray();
                foreach ($datum['course_contract_sign_up'] as &$item) {
					$res_course = (new CourseModel())->get($item['course_id']);
                    $item['course_name'] = $res_course['course_name'];
					$item['contract_type_text'] = (new DictionaryModel())->get($item['contract_type'])['name'];
					if($res_course['cost_type'] == 97){ //按期收费
						$item['unit'] = '期/('.$res_course['class_num'].'次课)';
					}else if($res_course['cost_type'] == 89){ //按次收费
						$item['unit'] = '课次';
					}else if($res_course['cost_type'] == 95){  //按小时收费
						$item['unit'] = '小时';
					}
						
                }
                $datum['grades_contract_sign_up'] = (new GradesContractModel())
                    ->where(['contract_id' => $datum['id']])
                    ->select()
                    ->toArray();
                foreach ($datum['grades_contract_sign_up'] as &$item) {
                    $item['grades_name'] = (new GradesDetailsModel())->get($item['grades_id'])['grades_name'];
					$item['contract_type_text'] = (new DictionaryModel())->get($item['contract_type'])['name'];
					$res_course = (new CourseModel())->get($item['course_id']);
					if($res_course['cost_type'] == 97){ //按期收费
						$item['unit'] = '期/('.$res_course['class_num'].'次课)';
					}else if($res_course['cost_type'] == 89){ //按次收费
						$item['unit'] = '课次';
					}else if($res_course['cost_type'] == 95){  //按小时收费
						$item['unit'] = '小时';
					}
						
                }
                $datum['goods_contract_sign_up'] = (new GoodsContractModel())
                    ->where(['contract_id' => $datum['id']])
                    ->select()
                    ->toArray();
                foreach ($datum['goods_contract_sign_up'] as &$item) {
                    $item['goods_name'] = (new GoodsModel())->get($item['goods_id'])['goods_name'];
					$item['contract_type_text'] = (new DictionaryModel())->get($item['contract_type'])['name'];
					$item['unit'] = (new GoodsModel())->get($item['goods_id'])['unit'];
                }
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/19.
     *
     * @param $params
     *
     * @return array
     */
    public function orderEdit($params)
    {
      	try {
            (new ContractModel())->save(['out_remark' => $params['out_remark'], 'in_remark' => $params['in_remark']], ['id' => $params['id']]);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
	 * 项目详情
	 * User: chenben
	 * Date: 2020/04/04
	 *
	 * @param $params
	 * @return array
	 */
    public function projectDetail($params)
    {
        try {
		$contract['id'] = $params['id'];
        //资金分配
        $Project_list = [];
        $res_course_contract = (new CourseContractModel())
			->where(['contract_id' => $contract['id']])
			->order('id desc')
			->select();
        foreach ($res_course_contract as $value){
                    $item = [];
                    if(($value['net_receipts'] - $value['assessed_amount']) <= $value['payment']){  //物品已经全额付款
                        $course_name =  CourseModel::get(['id' => $value['course_id']])['course_name'];
                        $arrears_amount = ($value['payment'] - ($value['net_receipts'] - $value['assessed_amount'])) / 100;
                        if(($value['net_receipts'] - $value['assessed_amount']) == $value['payment']){
                            $item['project_title'] = $course_name.'(已完缴)';
                        }else{
                            $item['project_title'] = $course_name.'(超缴'.$arrears_amount.'元)';
                        }
                    }else{
                        $course_name =  CourseModel::get(['id' => $value['course_id']])['course_name'];
                        $arrears_amount = (($value['net_receipts'] - $value['assessed_amount']) - $value['payment'] ) / 100;
                        $item['project_title'] = $course_name.'(欠缴'.$arrears_amount.'元)';
                    }
                    $item['project_id'] = $value['id'].'-1';//课程
                    $item['project_type'] = 1;
                    $Project_list[] = $item;
        }
        $res_grades_contract = (new GradesContractModel())
			->where(['contract_id' => $contract['id']])
			->order('id desc')
			->select();
        foreach ($res_grades_contract as $value){
                    $item = [];
                    if(($value['net_receipts'] - $value['assessed_amount']) <= $value['payment']){  //物品已经全额付款
                        $grades_name = GradesDetailsModel::get(['id' => $value['grades_id']])['grades_name'];
                        $arrears_amount = ($value['payment'] - ($value['net_receipts'] - $value['assessed_amount'])) / 100;
                        if(($value['net_receipts'] - $value['assessed_amount']) == $value['payment']){
                            $item['project_title'] = $grades_name.'(已完缴)';
                        }else{
                            $item['project_title'] = $grades_name.'(超缴'.$arrears_amount.'元)';
                        }
                    }else{
                        $grades_name = GradesDetailsModel::get(['id' => $value['grades_id']])['grades_name'];
                        $arrears_amount = (($value['net_receipts'] - $value['assessed_amount']) - $value['payment'])/ 100;
                        $item['project_title'] =$grades_name.'(欠缴'.$arrears_amount.'元)';
                    }
                    $item['project_id'] = $value['id'].'-2';//班级
                    $item['project_type'] = 2;
                    $Project_list[] = $item;
        }

        $res_goods_contract = (new GoodsContractModel())
			->where(['contract_id' => $contract['id']])
			->order('id desc')
			->select();
        foreach ($res_goods_contract as $value){
                    $item = [];
                    if(($value['net_receipts'] - $value['assessed_amount']) <= $value['payment']){  //物品已经全额付款
                       continue;
                    }else{
                        $goods_name = GoodsModel::get(['id' => $value['goods_id']])['goods_name'];
                        $arrears_amount = (($value['net_receipts'] - $value['assessed_amount']) - $value['payment'])/ 100;
                        $item['project_title'] =$goods_name.'(欠缴'.$arrears_amount.'元)';
                    }
                    $item['project_id'] = $value['id'].'-3';//物品
                    $item['project_type'] = 3;
                    $Project_list[] = $item;
        }
		$this->data = $Project_list;
        } catch (\Exception $e) {
            $this->errorMessage($e, '');
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/19.
     *
     * @return array
     */
    public function pickUpInformation()
    {
        try {
            $this->data['receivables'] = (new DictionaryModel())
                ->where(['type'=>24,'status'=>1])
                ->field('id,name')
                ->select()
                ->toArray()
            ;
            $this->data['payment_method'] = (new DictionaryModel())
                ->where(['type'=>20,'status'=>1])
                ->field('id,name')
                ->select()
                ->toArray()
            ;
            $this->data['receipt_number'] = 'PZ'.time();
            $this->data['payee'] = (new UserModel())->get(xcxapi_get_current_user_id())->toArray();
            $this->data['user'] = (new UserModel())
                ->where(['company_id' => xcxapi_get_current_company_id()])
                ->select()
                ->toArray();
            $this->data['campus'] = (new CampusModel())
                ->where(['id' => ['in', xcxapi_get_current_campus_id()]])
                ->select()
                ->toArray();
				
			$where_campus = [];
			if(xcxapi_get_current_wtype() != 1){
			  $where_campus['company_id'] =  xcxapi_get_current_company_id();
			}
			$this->data['campus_allocated'] = (new CampusModel())
                ->where($where_campus)
                ->select()
                ->toArray();
        } catch (\Exception $e) {
            $this->errorMessage($e, '');
        }

        return $this->return;
    }

    /**
     * 收款
     * User: wufeng
     * Date: 2020/02/21.
     *
     * @param $params
     *
     * @return array
     */
    public function receivables($params)
    {
        try {
            $data['contract_number'] = $params['contract_number']; // 合同编号
            $data['receipt_number'] = $params['receipt_number']; // 收款凭证号
            $data['flow_number'] = 'LSH'.date('md').$params['id']; // 流水号
            $data['campus_id'] = xcxapi_get_current_campus_id(); // 收款校区
            $data['assignment'] = $params['assignment']; // 收款归属
            $data['payee'] = $params['payee']; // 收款人
            $data['amount'] = $params['amount']; // 收款金额
            $data['paydate'] = date('Y-m-d'); // 收款日期
            $data['payment_method'] = $params['payment_method']; // 支付方式
            $data['audio'] = $params['audio']; // 音频
            $data['audio_duration'] = $params['audio_duration']; // 音频时长
            $data['video'] = $params['video']; // 视频
            $data['picture'] = $params['picture']; // 图片
            $data['remark'] = $params['remark']; // 收款备注
            Db::name('edu_receivables')->insert($data);
            $pay_flow = [];
            //			$pay_flow[] = ;
            (new ReceivablesModel())->save($data);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 学费分配
     * User: wufeng
     * Date: 2020/02/21.
     *
     * @param $params
     *
     * @return array
     */
    public function tuitionAllocation($params)
    {
        try {
            if (5 === (int) xcxapi_get_current_wtype()) {
                $where['payee'] = xcxapi_get_current_user_id();
            } else {
                $where['campus_id'] = ['in', xcxapi_get_current_campus_id()];
            }
            $this->data = (new ReceivablesModel())
                ->where($where)
                ->order('id desc')
                ->select()
                ->toArray();
            foreach ($this->data as &$datum) {
                $contract = (new ContractModel())->get(['contract_number' => $datum['contract_number']]);
                if (false !== strpos($datum['contract_number'], 'CZ')) {
                    $datum['order_status'] = 2;
                } else {
                    $datum['order_status'] = 1;
                }
                $datum['total_amount'] = $contract['total_amount'];
                $datum['create_time'] = $contract['create_time'];
                $datum['student_name'] = $contract['student_name'];
                $datum['course_contract_sign_up'] = (new CourseContractModel())
                    ->where(['contract_id' => $contract['id']])
                    ->select()
                    ->toArray();
                foreach ($datum['course_contract_sign_up'] as &$item) {
                    $item['course_name'] = (new CourseModel())->get($item['course_id'])['course_name'];
                }
                $datum['grades_contract_sign_up'] = (new GradesContractModel())
                    ->where(['contract_id' => $contract['id']])
                    ->select()
                    ->toArray();
                foreach ($datum['grades_contract_sign_up'] as &$item) {
                    $item['grades_name'] = (new GradesDetailsModel())->get($item['grades_id'])['grades_name'];
                }
                $datum['goods_contract_sign_up'] = (new GoodsContractModel())
                    ->where(['contract_id' => $contract['id']])
                    ->select()
                    ->toArray();
                foreach ($datum['goods_contract_sign_up'] as &$item) {
                    $item['goods_name'] = (new GoodsModel())->get($item['goods_id'])['goods_name'];
                }
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }
	
	 /**
     * 添加业绩
     * User: chenben
     * Date: 2020/03/22.
     *
     * @param $params
     *
     * @return array
     */
    public function addAchievement($params)
    {
        try {
			//校区业绩
			if(isset($params['campus_id']) && '' !== $params['campus_id'] && null !== $params['campus_id'] && isset($params['campus_department_id']) && null !== $params['campus_department_id'] && '' !== $params['campus_department_id']){
				$receivablesRes = (new ReceivablesModel())->get($params['id']);
				$data = [];
				$data['campus_id_all'] = $params['campus_id'];
				$data['campus_id_all_text'] = (new CampusModel())->get($params['campus_id'])['campus_name'];
				$data['assignment_all'] = $params['campus_department_id'];
				$data['assignment_all_text'] = (new DictionaryModel())->get($params['campus_department_id'])['name'];
				$data['rate_all'] = $params['campus_rate'];
				$money = round($receivablesRes['amount'] * ($params['campus_rate'] / 100));
				$data['rate_all_money'] = $money;
				$data['amount_already_all'] = $receivablesRes['amount'];
				$data['operator'] = xcxapi_get_current_user_id();
				$data['receipt_number'] = $receivablesRes['receipt_number'];
				$data['contract_number'] = $receivablesRes['contract_number'];
				$data['status'] = 2;
				Db::name('edu_performance_allocation_campus')->insert($data);
			}
			
			//个人业绩
			if(isset($params['only_id']) && '' !== $params['only_id'] && null !== $params['only_id'] && isset($params['only_department_id']) && null !== $params['only_department_id'] && '' !== $params['only_department_id']){
				$receivablesRes = (new ReceivablesModel())->get($params['id']);
				$data = [];
				$data['campus_id'] = $receivablesRes['campus_id'];
				$data['payee_only'] = $params['only_id'];
				$data['payee_only_text'] = (new UserModel())->get($params['only_id'])['name'];
				$data['assignment_only'] = $params['only_department_id'];
				$data['assignment_only_text'] = (new DictionaryModel())->get($params['only_department_id'])['name'];
				$data['rate_only'] = $params['only_rate'];
				$money = round($receivablesRes['amount'] * ($params['only_rate'] / 100));
				$data['rate_only_money'] = $money;
				$data['amount_already_only'] = $receivablesRes['amount'];
				$data['operator'] = xcxapi_get_current_user_id();
				$data['receipt_number'] = $receivablesRes['receipt_number'];
				$data['contract_number'] = $receivablesRes['contract_number'];
				$data['status'] = 2;
				Db::name('edu_performance_allocation_only')->insert($data);
			}
       
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 业绩分配
     * User: wufeng
     * Date: 2020/03/20.
     *
     * @param $params
     *
     * @return array
     */
    public function performanceAllocation($params)
    {
        try {
            $this->data['allocationCampus'] = (new AllocationCampusModel())
                ->where(['receipt_number' => $params['receipt_number'],'status'=>2])
                ->order('id desc')
                ->select()
                ->toArray();
            $this->data['allocationOnly'] = (new AllocationOnlyModel())
                ->where(['receipt_number' => $params['receipt_number'],'status'=>2])
                ->order('id desc')
                ->select()
                ->toArray();
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/21.
     *
     * @param $params
     *
     * @return array
     */
    public function performanceDel($params)
    {
        try {
            if (1 === (int) $params['api_type']) {
                (new AllocationCampusModel())->where(['id' => $params['id']])->delete();
            } elseif (2 === (int) $params['api_type']) {
                (new AllocationOnlyModel())->where(['id' => $params['id']])->delete();
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 订单详情
     * User: wufeng
     * Date: 2020/02/21.
     *
     * @param $params
     *
     * @return array
     */
    public function orderDetail($params)
    {
        try {
            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 订单退费
     * User: wufeng
     * Date: 2020/02/21.
     *
     * @param $params
     *
     * @return array
     */
    public function orderRefund($params)
    {
        try {
			if($params['api_type'] == 2){
				$contract = (new ContractModel())->get(['id' => $params['id']]);
				$contract['total_amount'] = $contract['total_amount'] / 100;
				$contract['amount'] = $contract['amount'] / 100;
				$contract['balance'] = $contract['balance'] / 100;
				$contract['account_balance'] = ((new StudentModel())->get(['id' => $contract['student_id']])['storedvalue']) / 100;  //该学生账户余额
				$contract['receipt_number'] = 'TK'.date("Ymd").time();
				if($contract['signing_type'] == 114){  //储值新签
					$contract['order_type'] = 1;
				}else if($contract['signing_type'] == 75){  //常规新签
					$contract['order_type'] = 0;
				}
				$this->data = $contract;
			}else if($params['api_type'] == 1){
				$Project_list = [];
				$contract = (new ContractModel())->get(['id' => $params['id']]);
				$contract['total_amount'] = $contract['total_amount'] / 100;
				$contract['amount'] = $contract['amount'] / 100;
				$contract['balance'] = $contract['balance'] / 100;
				$contract['account_balance'] = (StudentModel::get(['id' => $contract['student_id']])['storedvalue']) / 100;  //该学生账户余额
				$contract['receipt_number'] = 'TK'.date("Ymd").time();

				$payment_balance = (new GoodsContractModel())->where(['contract_id' => $contract['id']])->sum('payment_balance');
				$contract['goods_payment_balance'] = $payment_balance / 100;

				//资金分配
				$res_course_contract = (new CourseContractModel())->where(['contract_id' => $contract['id']])->select();
				foreach ($res_course_contract as $value){
					if($value['payment_balance'] > 0) {
						$item = [];
						$item['project_title'] = CourseModel::get(['id' => $value['course_id']])['course_name'];
						$item['project_id'] = $value['id'];//课程
						$item['project_type'] = 1;//课程
						$item['project_payment_balance'] = $value['payment_balance'] / 100;
						$item['project_amount'] = $item['project_payment_balance'];
						$Project_list[] = $item;
					}
				}
				$res_grades_contract = (new GradesContractModel())->where(['contract_id' => $contract['id']])->select();
				foreach ($res_grades_contract as $value){
					if($value['payment_balance'] > 0) {
						$item = [];
						$item['project_title'] = GradesDetailsModel::get(['id' => $value['grades_id']])['grades_name'];
						$item['project_id'] = $value['id'];
						$item['project_type'] = 2;//班级
						$item['project_payment_balance'] = $value['payment_balance'] / 100;
						$item['project_amount'] = $item['project_payment_balance'];
						$Project_list[] = $item;
					}
				}

				$res_goods_contract = ((new GoodsContractModel()))->where(['contract_id' => $contract['id']])->select();
				foreach ($res_goods_contract as $value){
					if($value['payment_balance'] > 0) {
						$item = [];
						$item['project_title'] = GoodsModel::get(['id' => $value['goods_id']])['goods_name'];
						$item['project_id'] = $value['id'];
						$item['project_type'] = 3;//物品
						$item['project_payment_balance'] = $value['payment_balance'] / 100;
						$item['project_amount'] = $item['project_payment_balance'];
						$Project_list[] = $item;
					}
				}

				if($contract['account_balance'] > 0) {
					$item = [];
					$item['project_title'] = '储值账户';
					$item['project_id'] = $contract['student_id'];
					$item['project_type'] = 4;//储值
					$item['project_payment_balance'] = $contract['account_balance'];
					$item['project_amount'] = $item['project_payment_balance'];
					$Project_list[] = $item;
				}
				$contract['project_list'] = $Project_list;
				$this->data = $contract;
			}
			
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }
	
	
	/**
     * 订单退费提交
     * User: chenben
     * Date: 2020/04/25.
     *
     * @param $params
     *
     * @return array
     */
    public function saverefund($params)
    {
        try {
			
          if($params['api_type'] == 1){  //订单退费
                $contract_id = $params['contract_id']; //合同ID
                $data_ = (new ContractModel())->get(['id' => $contract_id]);
                $data_refund['contract_number'] = $data_['contract_number']; //合同号
                $data_refund['student_name'] = $data_['student_name']; //姓名
                $data_refund['total_amount'] = $data_['total_amount']; //总额
                $data_refund['amount'] = $data_['amount']; //已收
                $data_refund['experienced_person'] = $params['experienced_person']; //经手人
                $data_refund['refund_channel'] = $params['refund_channel']; //退款通道
                $data_refund['receipt_number'] = $params['receipt_number']; //退款凭证
                $data_refund['campus_id'] = $data_['campus_id']; //退款校区
                $data_refund['campus_name'] = CampusModel::get(['id' => $data_['campus_id']])['campus_name']; //退款校区名称

                $json = $params['json'];
                $refund_amount = 0; //退款金额
                $amount_project = 0; //项目金额
                for ($i = 0; $i < count($json); $i++) {
                    $item = $json[$i];
                    $id = $item['project_id'];  //id
                    $type = $item['project_type']; //类型 1:课程  2:班级  3:物品  4:账户
                    $amount = $item['project_amount']*100; //金额
                    $refund_amount= $refund_amount +  $amount; //退款金额

                    if($type == 1){
                        $amount_project = $amount_project + $amount;
                        $res_course = (new CourseContractModel())->get(['id' => $id]);
                        $payment_balance = ($res_course['payment_balance'] - $amount);
                        $payment = ($res_course['payment'] - $amount);
                        (new CourseContractModel())->where(['id' => $id])->update(['payment_balance' => $payment_balance, 'payment' => $payment]);


                        //更新合同应收分配课时
                        $price_ = round(((($res_course['net_receipts'] - $res_course['assessed_amount']))/($res_course['class_num'])),2); //折后应收 - 分摊金额
                        $nums = round(($payment / $price_),2);

                        $course_arr = explode(',',$data_['course']);
                        $key = array_search($res_course['course_id'], $course_arr);
                        $course_paid_nums_arr = explode(',',$data_['course_paid_nums']);
                        $course_paid_nums_arr[$key] = $nums;
                        $course_paid_nums = implode(',',$course_paid_nums_arr);

                        (new ContractModel())->where(['id' => $contract_id])->update(['course_paid_nums' => $course_paid_nums]);


                        //退费流水
                        CommonService::writeFlowRecord($data_['contract_number'], 2, $amount, '记录订单课程退款流水', $data_['campus_id'], $params['receipt_number'], $params['refund_channel']);
                    }else if($type == 2){
                        $amount_project = $amount_project + $amount;
                        $res_grades = (new GradesContractModel())->get(['id' => $id]);
                        $payment_balance = ($res_grades['payment_balance'] - $amount);
                        $payment = ($res_grades['payment'] - $amount);
                        (new GradesContractModel())->where(['id' => $id])->update(['payment_balance' => $payment_balance, 'payment' => $payment]);

                        $price_ = round(((($res_grades['net_receipts'] - $res_grades['assessed_amount']))/($res_grades['class_num'])),2); //折后应收 - 分摊金额
                        $nums = round(($payment / $price_),2);

                        $grades_arr = explode(',',$data_['grades_course']);
                        $key = array_search($res_grades['course_id'], $grades_arr);
                        $grades_course_paid_nums_arr = explode(',',$data_['grades_course_paid_nums']);
                        $grades_course_paid_nums_arr[$key] = $nums;
                        $grades_course_paid_nums = implode(',',$grades_course_paid_nums_arr);

                        (new ContractModel())->where(['id' => $contract_id])->update(['grades_course_paid_nums' => $grades_course_paid_nums]);


                        //退费流水
                        CommonService::writeFlowRecord($data_['contract_number'], 2, $amount, '记录订单班级退款流水', $data_['campus_id'], $params['receipt_number'], $params['refund_channel']);
                    }else if($type == 3){
                        $amount_project = $amount_project + $amount;
                        $res_goods = (new GoodsContractModel())->get(['id' => $id]);
                        $payment_balance = ($res_goods['payment_balance'] - $amount);
                        $payment = ($res_goods['payment'] - $amount);
                        (new GoodsContractModel())->where(['id' => $id])->update(['payment_balance' => $payment_balance, 'payment' => $payment]);
                        //退费流水
                        CommonService::writeFlowRecord($data_['contract_number'], 2, $amount, '记录订单物品退款流水', $data_['campus_id'], $params['receipt_number'], $params['refund_channel']);
                    }else if($type == 4){
                        $res_student = (new StudentModel())->get(['id' => $id]);
                        $storedvalue = ($res_student['storedvalue'] - $amount);
                        (new StudentModel())->where(['id' => $id])->update(['storedvalue' => $storedvalue]);

                        $res_contract = (new ContractModel())->get(['id' => $contract_id]);
                        $contract_storedvalue = ($res_contract['storedvalue'] - $amount);
                        (new ContractModel())->where(['id' => $contract_id])->update(['storedvalue' => $contract_storedvalue]);

                        //退费流水
                        CommonService::writeFlowRecord($data_['contract_number'], 2, $amount, '记录订单储值退款流水', $data_['campus_id'], $params['receipt_number'], $params['refund_channel']);
                    }

                }

                //学费余额
                $payment_grades_balance = (new GradesContractModel())->where(['contract_id' => $contract_id])->sum('payment_balance');
                $payment_course_balance = (new CourseContractModel())->where(['contract_id' => $contract_id])->sum('payment_balance');
                $payment_money_balance = ($payment_course_balance + $payment_grades_balance); //班级与课程余额之和


                //项目总收
                $data_['amount'] = $data_['amount'] - $amount_project;
                //实收
                $data_['net_receipts'] = $data_['net_receipts'] - $amount_project;
                //欠费
                $data_['stay_amount'] = $data_['total_amount'] - $data_['amount'];

                (new ContractModel())->where(['id' => $contract_id])->update(['balance' => $payment_money_balance, 'amount' => $data_['amount'], 'net_receipts' => $data_['net_receipts'], 'stay_amount' => $data_['stay_amount']]);

              //  $data_refund['balance'] = $data_['balance']; //余额
				$data_refund['balance'] = $payment_money_balance; //余额
                $data_refund['refund_amount'] = $refund_amount;

                if (!(new RefundAmountModel())->save($data_refund)) {
                     throw new BaseException('REFUND_FAILED');
                }
   
            }else if($params['api_type'] == 2){   //储值退费
                //化成分
                $data['amount'] = $params['amount'] * 100;
                $data['total_amount'] = $params['total_amount'] * 100;
                $data['balance'] = ($params['balance'] - $params['refund_amount']) * 100;
                $data['refund_amount'] = $params['refund_amount'] * 100;
				$data['experienced_person'] = $params['experienced_person'];
			    $data['refund_channel'] = $params['refund_channel'];
				$data['receipt_number'] = $params['receipt_number'];
				$data['student_name'] = $params['student_name'];
				$data['contract_number'] = $params['contract_number'];
                $result_campus = (new ContractModel())->get(['contract_number' => $params['contract_number']]);
                $data['campus_id'] = $result_campus['campus_id'];  //校区ID
                $data['campus_name'] = (new CampusModel())->get(['id' => $result_campus['campus_id']])['campus_name']; //校区名字
                if (!(new RefundAmountModel())->save($data)) {
                   throw new BaseException('REFUND_FAILED');
                }
               
               
                $storedvalue = (new StudentModel())->get(['id' => $result_campus['student_id']])['storedvalue'];
                $storedvalue = $storedvalue - $data['refund_amount'];
                if (!(new StudentModel())->where(['id' => $result_campus['student_id']])->update(['storedvalue' => $storedvalue])) {
                   throw new BaseException('UPDATE_ONLY_STORED_FAILED');
                }
                

                //退费流水
                CommonService::writeFlowRecord($params['contract_number'], 2, $params['refund_amount'], '记录订单储值退款流水', $data['campus_id'], $params['receipt_number'], $params['refund_channel']);

             
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 业绩分配记录
     * User: wufeng
     * Date: 2020/02/21.
     *
     * @param $params
     *
     * @return array
     */
    public function performanceDistributionRecord($params)
    {
        try {
            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 业绩分配
     * User: wufeng
     * Date: 2020/02/21.
     *
     * @param $params
     *
     * @return array
     */
    public function performanceDistribution($params)
    {
        try {
            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }
}
